package com.shareppy.nomrnaui;

import java.util.HashMap;
import java.util.Map;

import android.app.AlarmManager;
import android.app.Application;
import android.app.PendingIntent;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;

import com.shareppy.nomrnaui.annotations.Repeat;
import com.shareppy.nomrnaui.annotations.persistence.PersistenceUnit;
import com.shareppy.norman.sqlite.em.EMF;

public class NormanApp extends Application {

	private static Context appContext;
	private static Map<String, PendingIntent> pendingIntents;
	private static AlarmManager alarmManager;

	@Override
	public void onCreate() {
		super.onCreate();
		setAppContext(getApplicationContext());
		setupPersistenceUnit();
		setupRepeat();
	}

	private void setupRepeat() {
		Repeat repeat = getClass().getAnnotation(Repeat.class);
		if (repeat != null) {
			pendingIntents = new HashMap<String, PendingIntent>();
			alarmManager = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
			initRepeat(repeat.receiver(), repeat.name(), repeat.interval(),
					repeat.type());
		}
	}

	/**
	 * Actualizar un repeat por su nombre.
	 * 
	 * @param name
	 * @param interval
	 * @param type
	 */
	public static void initRepeat(Class<? extends BroadcastReceiver> receiver,
			String name, long interval, int type) {
		PendingIntent pendingIntent = getPendingIntent(name, receiver);
		alarmManager.setRepeating(type, 0, interval, pendingIntent);
	}

	/**
	 * Actualizar un repeat por su nombre.
	 * 
	 * @param name
	 * @param interval
	 * @param type
	 */
	public static void updateRepeat(String name, long interval, int type) {
		PendingIntent pendingIntent = getPendingIntent(name, null);
		alarmManager.setRepeating(type, 0, interval, pendingIntent);
	}

	private static PendingIntent getPendingIntent(String name,
			Class<? extends BroadcastReceiver> receiver) {
		PendingIntent pendingIntent = pendingIntents.get(name);
		if (pendingIntent == null && receiver != null) {
			Intent intent = new Intent(getAppContext(), receiver);
			pendingIntent = PendingIntent.getBroadcast(getAppContext(), 0,
					intent, 0);
			pendingIntents.put(name, pendingIntent);
		}
		return pendingIntent;
	}

	private void setupPersistenceUnit() {
		PersistenceUnit persistenceUnit = getClass().getAnnotation(
				PersistenceUnit.class);
		if (persistenceUnit != null) {
			EMF.configure(getAppContext(), persistenceUnit.name(),
					persistenceUnit.version(), persistenceUnit.entities());
		}
	}

	public static Context getAppContext() {
		return appContext;
	}

	public static void setAppContext(Context appContext) {
		NormanApp.appContext = appContext;
	}
}